/* eslint-disable consistent-return */
import Taro from '@tarojs/taro';
import { postOpenIdBind, postAuthUserLogin, getUerBindResult } from './services';

const APP_ID = '';

/**
 * @method 与服务端绑定小程序
 */
export const authLoginBind = async () => {
  const { openid, unionid } = Taro.getStorageSync('user');

  await postOpenIdBind({
    openId: openid,
    unionid,
    appId: APP_ID,
  });
};

/**
 * @method 获取sid和token
 */
export const checkUserIsBind = async () => {
  const { code } = await Taro.login();
  const user = Taro.getStorageSync('user') || {};

  const content = await postAuthUserLogin({
    jsCode: code,
    appId: APP_ID,
    newSso: true,
  });

  // 是否绑定过小程序
  const isBinded = content.token && content.sid;

  // 防止已登陆用户token和sid被覆盖
  if (!isBinded) {
    delete content.token;
    delete content.sid;
  }

  Taro.setStorageSync('user', {
    ...user,
    ...content,
  });

  return isBinded;
};

/**
 * @method 确认用户是否绑定小程序
 */
export const userHasBinding = async () => {
  const user = Taro.getStorageSync('user') || {};
  try {
    const res = await getUerBindResult({
      appId: APP_ID,
      sid: user?.sid,
      token: user?.token,
    });
    return res;
  } catch (error) {
    return false;
  }
};

/**
 * @method 弹窗提示用户绑定小程序
 */
export const hintUserBind = async () => {
  // 判断用户是否绑定
  const isBinded = await checkUserIsBind();

  // 获取用户本地缓存数据
  const user = Taro.getStorageSync('user');

  // 没有绑定小程序&&已经登录过的&&没有点击取消绑定的
  if (!isBinded && user.token && user.sid) {
    return new Promise<void>((resolve) => {
      Taro.modal.showModal({
        title: '提示',
        content: '您还没有微信授权,授权后登录更方便!',
        confirmText: '立即授权',
        showCancel: false,
        donotClose: true,
        success() {
          authLoginBind().then(() => {
            Taro.showToast({
              title: '授权成功',
              icon: 'success',
              duration: 1000,
            });
            resolve();
          });
        },
      });
    });
  }
};
